//
//  SecondRegisterController.m
//  JF_New_DYKT
//
//  Created by 陈雷 on 2017/8/24.
//  Copyright © 2017年 陈雷. All rights reserved.
//

#import "SecondRegisterController.h"
#import "ThirdRegisterController.h"


@interface SecondRegisterController ()

@property (nonatomic,assign) int CountdownTime;
@property (weak, nonatomic) IBOutlet UIButton *yzmBtn;
@property (nonatomic,strong) NSTimer *countDownTimer;
@property (weak, nonatomic) IBOutlet UILabel *bigTitleLb;

@property (weak, nonatomic) IBOutlet BaseTextfiled *phoneNumTf;

@property (weak, nonatomic) IBOutlet BaseTextfiled *yzmTf;



@end

@implementation SecondRegisterController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.CountdownTime = 60;
    
    if ([self.fromWhere isEqualToString:@"forgetPsd"]) {
        self.bigTitleLb.text = @"找回密码";
        
        self.login_registerModel = [[Login_registerModel alloc]init];
        
        
    }else if ([self.fromWhere isEqualToString:@"wx"] || [self.fromWhere isEqualToString:@"qq"]){
        self.bigTitleLb.text = @"绑定手机号";
    }
    self.phoneNumTf.keyboardType = UIKeyboardTypeNumberPad;
    self.yzmTf.keyboardType = UIKeyboardTypeNumberPad;
    [self notificationAction];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if ([self.fromWhere isEqualToString:@"forgetPsd"]) {
        UIButton *leftButton = [[UIButton alloc]init];
        leftButton.frame = CGRectMake(0, 0, 11, 20);
        [leftButton setBackgroundImage:[UIImage imageNamed:@"allBack.png"] forState:UIControlStateNormal];
        [leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *leftBarButtonItems = [[UIBarButtonItem alloc]initWithCustomView:leftButton];
        //解决按钮不靠左 靠右的问题.
        UIBarButtonItem *nagetiveSpacer = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                       target:nil action:nil];
        self.navigationItem.leftBarButtonItems = @[nagetiveSpacer, leftBarButtonItems];

    }
    
    self.navigationController.navigationBar.translucent = YES;
    
    [self.navigationController.navigationBar setShadowImage:[JFCrazyTool imageWithColor:[UIColor whiteColor]]];
    [self.navigationController.navigationBar setBackgroundImage:[JFCrazyTool imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    if ([self.fromWhere isEqualToString:@"forgetPsd"]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(swapAction) name:@"forgetPsd" object:nil];
    }


}

- (void)swapAction{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"dismissAction" object:nil userInfo:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"forgetPsd" object:nil];
    [self.countDownTimer invalidate];
    self.countDownTimer = nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)handleAcion:(UIButton *)sender {
    if (sender.tag == 100) {
        NSLog(@"下一步");
        ThirdRegisterController *thirdRegisterVc = [[ThirdRegisterController alloc]init];
        thirdRegisterVc.fromWhere = self.fromWhere;
        
        if (self.phoneNumTf.text.length <= 0) {
            [JKToast showWithText:@"请先输入您的手机号！"];
            return;
        }
        if (self.yzmTf.text.length <= 0) {
            [JKToast showWithText:@"请输入短信验证码"];
            return;
        }
        
        self.login_registerModel.code = self.yzmTf.text;
        self.login_registerModel.mobile = self.phoneNumTf.text;
        
        thirdRegisterVc.login_registerModel = self.login_registerModel;
        
        [self.navigationController pushViewController:thirdRegisterVc animated:YES];
    }else{
        NSLog(@"发送验证码");
        
        NSString *phoneC = [self.phoneNumTf.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        if (!phoneC || phoneC.length != 11) {
            [JKToast showWithText:@"请输入有效的手机号"];
            return;
        }
        
        [self.phoneNumTf resignFirstResponder];
        [self.yzmTf resignFirstResponder];

        [self sendMsg];
    }
}

#pragma mark- 发送短信
- (void)sendMsg{
    
    NSString *urlStr = [NSString stringWithFormat:@"%@user/User/sendCode",kDomainName];
    
    NSString *msgType = nil;//短信类型 reset忘记 regist注册
    
    if ([self.fromWhere isEqualToString:@"forgetPsd"]) {
        msgType = @"reset";
    }else{
        msgType = @"regist";
    }
    
    NSDictionary *paraDic = @{@"mobile":self.phoneNumTf.text,
                              @"type":msgType};
    
    BaseRequest *request =  [BaseRequest sharedBaseRequest];
    [request post:urlStr params:paraDic success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"1"] ) {
            [self.countDownTimer fire];
            self.yzmBtn.enabled = NO;
            [JKToast showWithText:responseObject[@"message"]];
        }else{
            
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];

}


- (NSTimer *)countDownTimer{

    if (!_countDownTimer) {
        _countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showYZMMessage) userInfo:nil repeats:YES];
    }
    return _countDownTimer;
}

- (void)showYZMMessage{
    self.CountdownTime--;
    
    if (self.CountdownTime <= 0) {
        
        [_countDownTimer invalidate];
        _countDownTimer = nil;
        self.CountdownTime = 60;
        [self.yzmBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        self.yzmBtn.enabled = YES;
        
    }else{
        
        [self.yzmBtn setTitle:[NSString stringWithFormat:@"%ds后重新发送",self.CountdownTime] forState:UIControlStateNormal];
        
    }

}


- (void)backAction{

    if ([self.fromWhere isEqualToString:@"forgetPsd"]) {
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    
    if ([self.navigationController respondsToSelector:@selector(pushViewController:animated:)])
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
    
}



- (void)notificationAction{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyBoardWillShow:(NSNotification *) note {
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘高度
    CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyBoardBounds.size.height;
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        self.view.transform = CGAffineTransformMakeTranslation(0, -keyBoardHeight+80);
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }
    
}

- (void)keyBoardWillHide:(NSNotification *) note {
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:note.userInfo];
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        self.view.transform = CGAffineTransformIdentity;
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }
}


@end
